package com.csc531.adapters;

/*
 * Copyright (C) 2008 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


/**
 * @author Javier Figueroa
 */

public class ManagerDbAdapter {

	//Classes 
    public static final String KEY_COURSE = "course";
    public static final String KEY_DUEDATE = "duedate";
    public static final String KEY_TITLE = "title";
    public static final String KEY_BODY = "body";
    public static final String KEY_ROWID = "_id";
    
    //Notes
    public static final String KEY_NOTE_TITLE = "title";
    public static final String KEY_NOTE_BODY = "body";
    
    //Settings
	public static final String EMAIL = "email";
	public static final String PASSWORD = "password";
	public static final String ENABLE_GOOGLE = "enabled";

	//DB settings names
    private static final String DATABASE_NAME = "HWManager";
    private static final String CLASSES_TABLE = "classes";
	private static final String SETTINGS_TABLE = "settings";
    private static final String NOTES_TABLE = "notes";
    private static final int DATABASE_VERSION = 3;
    
    //Create tables queries
    private static final String CLASSES_TABLE_CREATE =
            "create table " + CLASSES_TABLE + " (" + KEY_ROWID + " integer primary key autoincrement, "
                    + KEY_COURSE + " text not null, " + KEY_TITLE + " text not null, " 
                    + KEY_DUEDATE + " text not null, " + KEY_BODY + " text not null);";

    private static final String NOTES_TABLE_CREATE =
        "create table " + NOTES_TABLE + " (" + KEY_ROWID + " integer primary key autoincrement, "
                + KEY_TITLE + " text not null, " + KEY_BODY + " text not null);";
    

	private static final String SETTINGS_TABLE_CREATE =
		"create table "+SETTINGS_TABLE+" (_id integer primary key autoincrement, " + EMAIL + " text not null, "
		+ PASSWORD + " text not null, " + ENABLE_GOOGLE + " text not null);";


    private static final String TAG = "ManagerDbAdapter";
    private DatabaseHelper _mDbHelper;
    private SQLiteDatabase _mDb;
    private final Context _mCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper 
    {

        DatabaseHelper(Context context) 
        {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) 
        {
            db.execSQL(CLASSES_TABLE_CREATE);
            db.execSQL(NOTES_TABLE_CREATE);
            db.execSQL(SETTINGS_TABLE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
        {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS " + CLASSES_TABLE);
            db.execSQL("DROP TABLE IF EXISTS " + NOTES_TABLE);
            db.execSQL("DROP TABLE IF EXISTS " + SETTINGS_TABLE);
            onCreate(db);
        }
    }

    public ManagerDbAdapter(Context ctx) 
    {
        this._mCtx = ctx;
    }

    public ManagerDbAdapter open() throws SQLException 
    {
        _mDbHelper = new DatabaseHelper(_mCtx);
        _mDb = _mDbHelper.getWritableDatabase();
        
        return this;
    }
    
    public void close() {
        _mDbHelper.close();
    }

    public long createTask(String course, String title, String duedate, String body) 
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_COURSE, course);
        initialValues.put(KEY_TITLE, title);
        initialValues.put(KEY_DUEDATE, duedate);
        initialValues.put(KEY_BODY, body);
        
        return _mDb.insert(CLASSES_TABLE, null, initialValues);
    }

    public boolean deleteTask(int rowId) 
    {
    	Log.v(TAG, "deleting: with id: "+ rowId);
        return _mDb.delete(CLASSES_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }
    
    public boolean deleteAllTasks() 
    {
    	_mDb.delete(CLASSES_TABLE, null, null) ;
        _mDbHelper.onUpgrade(_mDb, 0, 1);
    	return resetRowId(CLASSES_TABLE);
    }

    public Cursor fetchAllTasks() 
    {
    	//new String[] {KEY_ROWID, KEY_COURSE, KEY_TITLE, KEY_DUEDATE,
          //      KEY_BODY}
        return _mDb.query(CLASSES_TABLE, null, null, null, null, null, null);
    }

    public Cursor fetchTask(long rowId) throws SQLException 
    {
        Cursor mCursor = _mDb.query(true, CLASSES_TABLE, new String[] {KEY_ROWID, KEY_COURSE,
                        	KEY_TITLE, KEY_DUEDATE, KEY_BODY}, KEY_ROWID + "=" + rowId, null,
                        	null, null, null, null);
        
        if (mCursor != null) 
        {
            mCursor.moveToFirst();
        }
        
        return mCursor;
    }
    
    public Cursor fetchAllCourses()
    {
        Cursor mCursor = _mDb.query(true, CLASSES_TABLE, new String[] {
                       		KEY_COURSE},
                       		null,null,
                       		null, null, null, null);

        if (mCursor != null) 
        {
            mCursor.moveToFirst();
        }
        
        return mCursor;
    }

    public boolean updateTask(long rowId, String course, String title, String duedate, String body) 
    {
        ContentValues args = new ContentValues();
        args.put(KEY_COURSE, course);
        args.put(KEY_TITLE, title);
        args.put(KEY_DUEDATE, duedate);
        args.put(KEY_BODY, body);

        return _mDb.update(CLASSES_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
    
    public long createNote(String title, String body) 
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_TITLE, title);
        initialValues.put(KEY_BODY, body);
        
        return _mDb.insert(NOTES_TABLE, null, initialValues);
    }

    public boolean deleteNote(int rowId) 
    {
    	Log.v(TAG, "deleting: with id: "+ rowId);
        
    	return _mDb.delete(NOTES_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }
    
    public boolean deleteAllNotes() 
    {
    	_mDb.delete(NOTES_TABLE, null, null) ;
        _mDbHelper.onUpgrade(_mDb, 0, 1);
    	
        return resetRowId(NOTES_TABLE);
    }

    public Cursor fetchAllNotes() 
    {
        return _mDb.query(NOTES_TABLE, null, null, null, null, null, null);
    }

    public Cursor fetchNote(long rowId) throws SQLException 
    {
        Cursor mCursor =
                _mDb.query(true, NOTES_TABLE, new String[] {KEY_ROWID,
                        KEY_TITLE, KEY_BODY}, KEY_ROWID + "=" + rowId, null,
                        null, null, null, null);
        
        if (mCursor != null) 
        {
            mCursor.moveToFirst();
        }
        
        return mCursor;
    }
    
    public boolean updateNote(long rowId, String title, String body) 
    {
        ContentValues args = new ContentValues();
        args.put(KEY_TITLE, title);
        args.put(KEY_BODY, body);

        return _mDb.update(NOTES_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
    
    public boolean resetRowId(String tableName) 
    {
    	ContentValues args = new ContentValues();
    	args.put(KEY_ROWID, 0);
    	
    	return _mDb.update(tableName, args, null, null) > 0;
    }
    
    public long AddGoogleCredentials(String email, String password, String enabled)
	{
		ContentValues values = new ContentValues();
		values.put(EMAIL, email);
		values.put(PASSWORD, password);
		values.put(ENABLE_GOOGLE, enabled);

		return _mDb.insert(SETTINGS_TABLE, null, values);
	}

	public boolean updateGoogleCredentials(String email, String password, String enabled) 
	{
		ContentValues values = new ContentValues();
		values.put(EMAIL, email);
		values.put(PASSWORD, password);
		values.put(ENABLE_GOOGLE, enabled);
		Log.v(TAG, "email "+email);
		Log.v(TAG, "password "+password);
		Log.v(TAG, "enabled "+enabled);

		return _mDb.update(SETTINGS_TABLE, values, EMAIL + "=" + email, null) > 0;
	}

	public Cursor FetchEmailAndPasswordAndEnable() throws SQLException 
	{
		Cursor mCursor =
			_mDb.query(true, SETTINGS_TABLE, new String[] {EMAIL,PASSWORD,ENABLE_GOOGLE}, null, null,
					null, null, null, null);

		if (mCursor != null) 
		{
			mCursor.moveToFirst();
		}

		return mCursor;
	}
	
	public Cursor FetchEmailAndPasswordAndEnable(String email) throws SQLException
	{
		Cursor mCursor =
			_mDb.query(true, SETTINGS_TABLE, new String[] {EMAIL,PASSWORD,ENABLE_GOOGLE}, EMAIL + "=" + email, null,
					null, null, null, null);

		if (mCursor != null) 
		{
			mCursor.moveToFirst();
		}

		return mCursor;
	}
}
